package kr.couponplay.android.support;

import java.util.ArrayList;
import java.util.List;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.Category;

import org.json.JSONArray;
import org.json.JSONException;

public class CategoryUtils {
	
	public static void setting(String jsonString) {
		try {
			JSONArray jSONArray = new JSONArray(jsonString);
			List<Category> categories = parseCategories(jSONArray);
			List<Category> mainCategories = makeMainCategory(categories);
			AppContext.setMainCategories(mainCategories);
		} catch (Exception e) {
			throw new IllegalArgumentException(e.getMessage(), e);
		}
	}
	
	private static List<Category> parseCategories(JSONArray jSONArray) throws JSONException {
		List<Category> categories = new ArrayList<Category>();
		for (int i = 0; i < jSONArray.length(); i++) {
			Category category = new Category();
			category.setId(jSONArray.getJSONObject(i).getInt("id"));
			category.setName(jSONArray.getJSONObject(i).getString("name"));
			category.setCode(jSONArray.getJSONObject(i).getString("code"));
			category.setLevelNo(jSONArray.getJSONObject(i).getInt("levelNo"));
			category.setOrderNo(jSONArray.getJSONObject(i).getInt("orderNo"));
			category.setParentId(jSONArray.getJSONObject(i).getInt("parentId"));
			categories.add(category);
		}
		return categories;
	}
	
	private static List<Category> makeMainCategory(List<Category> categories) {
		List<Category> mainCategories = new ArrayList<Category>();
		for (Category category : categories) {
			if (category.getLevelNo() == 1) {
				category.addChild(category.newFirstSubCategory());	//서브카테고리에 "쇼핑 전체" 같은 전체 메뉴 추가 함.
				mainCategories.add(category);
			}
		}
		for (Category category : categories) {
			if (category.getLevelNo() == 2) {
				Category groupCategory = getMainCategory(mainCategories, category.getParentId());
				if (groupCategory != null) {
					groupCategory.addChild(category);
				}
			}
		}
		
		return mainCategories;
	}

	private static Category getMainCategory(List<Category> mainCategories, int parentId) {
		for (Category category : mainCategories) {
			if (category.getId() == parentId) {
				return category;
			}
		}
		return null;
	}

//	private static List<List<Category>> makeSubCategory(List<Category> categories) {
//		List<List<Category>> subCategories = new ArrayList<List<Category>>();
//		for (Category category : categories) {
//			if (category.getLevelNo() == 2) {
//				List<Category> children = subCategories.get(category.getParentId());
//				if (children == null) {
//					children = new ArrayList<Category>();
//				}
//				children.add(category);
//				subCategories.put(category.getParentId(), children);
//			}
//		}
//		return subCategories;
//	}
}
